package cn.echo.ecc.mq.listener;


import cn.echo.ecc.domain.PayOrder;
import cn.echo.ecc.dto.PayApplyNotifyTxParamDto;
import cn.echo.ecc.dto.PayExtParamDto;
import cn.echo.ecc.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-pay-notify-producer-group")
public class PayNotifyTxListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayOrderService payOrderService;

    /**
     * 执行本地事务
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            log.info("开始执行异步通知本地事务！");
            if (arg == null) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 转换参数类型
            PayApplyNotifyTxParamDto payApplyNotifyTxParamDto = JSON.parseObject(arg.toString(), PayApplyNotifyTxParamDto.class);
            // 修改支付单状态和保存支付流水
            payOrderService.savePayOrderAndPayFlow(payApplyNotifyTxParamDto);
            log.info("异步通知本地事务执行成功！");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("异步通知本地事务执行失败！");
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 检查本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            log.info("开始回查异步通知本地事务执行结果！");
            // 防御性编程
            byte[] bytes = (byte[])message.getPayload();
            if (bytes == null) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 转换参数类型，业务校验
            String strParam = new String(bytes, StandardCharsets.UTF_8);
            PayExtParamDto payExtParamDto = JSON.parseObject(strParam, PayExtParamDto.class);
            if (payExtParamDto == null) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 回查本地事务执行结果
            PayOrder payOrder = payOrderService.selectByOrderNo(payExtParamDto.getOrderNo());
            if (payOrder != null && payOrder.getPayStatus() != PayOrder.SUCCESS_STATUS) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            log.info("回查异步通知本地事务执行成功！");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("回查异步通知本地事务执行失败！");
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
